<?php

declare(strict_types=1);

namespace app\controller\user;

use app\BaseController;
use app\model\User;
use app\service\factory\ResponseFactory;
use app\service\user\ProfileService;
use app\validate\user\ProfileValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Profile extends BaseController
{
    public function show(ProfileService $profileService): Response
    {
        $user = $this->resolveUser();
        if (!$user) {
            return json(ResponseFactory::error('用户不存在', 404));
        }

        try {
            $data = $profileService->getProfile($user);
            return json(ResponseFactory::success($data));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function update(ProfileService $profileService): Response
    {
        $user = $this->resolveUser();
        if (!$user) {
            return json(ResponseFactory::error('用户不存在', 404));
        }

        $payload = $this->request->only([
            'nickname',
            'real_name',
            'email',
            'avatar',
        ], $this->request->method());

        try {
            $this->validate($payload, ProfileValidate::class . '.updateProfile');
            $updated = $profileService->updateProfile($user, $payload);
            $data = $profileService->getProfile($updated);

            return json(ResponseFactory::success($data, '资料已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function updatePassword(ProfileService $profileService): Response
    {
        $user = $this->resolveUser();
        if (!$user) {
            return json(ResponseFactory::error('用户不存在', 404));
        }

        $payload = $this->request->only([
            'current_password',
            'new_password',
            'confirm_password',
        ], $this->request->method());

        try {
            $this->validate($payload, ProfileValidate::class . '.updatePassword');
            $profileService->updatePassword(
                $user,
                (string) $payload['current_password'],
                (string) $payload['new_password']
            );

            return json(ResponseFactory::success(true, '密码已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function updateOrg(int $id, ProfileService $profileService): Response
    {
        $user = $this->resolveUser();
        if (!$user) {
            return json(ResponseFactory::error('用户不存在', 404));
        }

        $payload = $this->request->only([
            'contact',
            'shipping_address',
            'receiving_address',
        ], $this->request->method());

        try {
            $this->validate($payload, ProfileValidate::class . '.updateOrg');
            $org = $profileService->updateOrgSettings($user, $id, $payload);

            return json(ResponseFactory::success(['org' => $org], '组织信息已更新'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    private function resolveUser(): ?User
    {
        $userId = (int) ($this->request->user_id ?? 0);
        if ($userId <= 0) {
            return null;
        }

        return User::find($userId);
    }
}
